<template>
    <div class="login-container">
        <el-card class="login-card">
            <template #header>
                <h2>系统登录</h2>
            </template>
            <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username" placeholder="用户名">
                        <template #prefix>
                            <el-icon>
                                <User />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="loginForm.password" type="password" placeholder="密码">
                        <template #prefix>
                            <el-icon>
                                <Lock />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { login } from '@/api/api'
import { setToken } from '@/utils/auth'

const router = useRouter()
const loginFormRef = ref(null)

const loginForm = reactive({
    username: 'admin',
    password: 'admin123456'
})

const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const handleLogin = () => {
    loginFormRef.value.validate((valid) => {
        if (valid) {
            login(loginForm).then(res => {
                console.log(res)
                setToken(res.data.token)
                ElMessage.success('登录成功')
                router.push('/')
            }).catch(err => {
                console.log(err)
                ElMessage.error(err.message)
            })
        }
    })
}
</script>

<style scoped>
.login-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f3f3f3;
}

.login-card {
    width: 400px;
}

.login-card :deep(.el-card__header) {
    text-align: center;
}
</style>